package com.xxwy.ddu.common.autowired.email;

import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * @author xxwy
 * on 2018/8/9 0009
 */
@Service
@Primary
public class EmailServiceImpl  implements EmailService{

    @Autowired
    JavaMailSender mailSender;

    @Value("${spring.mail.fromEmail}")
    private String fromEmail;

    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    /**
     * 可以配置全局fromEmail，mail.fromEmail
     * 发送简单信息
     */
    @Override
    public void sendSimpleMail(EmailInfo info){
        //判空
        if(!Strings.isNullOrEmpty(info.getToEmail())) {
            if (fromEmail != null) {
                info.setFormEmail(fromEmail);
            }
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(info.getToEmail());
            message.setText(info.getText());
            message.setSubject(info.getSubject());
            try {
                mailSender.send(message);
                logger.info("简单邮件已经发送");
            } catch (Exception e) {
                logger.error("发送简单邮件异常=={}", e);
            }
        }else {
            logger.error("发送人为空具体信息{}", info);
        }
    }

    /**
     * 发送Html信息
     * @param info
     */
    @Override
    public void sendHtmlMail(EmailInfo info){
        if(!Strings.isNullOrEmpty(info.getToEmail())) {
            if (fromEmail != null) {
                info.setFormEmail(fromEmail);
            }
            try {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(fromEmail);
                helper.setTo(info.getToEmail());
                helper.setText(info.getText(),true);
                helper.setSubject(info.getSubject());
                mailSender.send(message);
                logger.info("简单邮件已经发送");
            } catch (Exception e) {
                logger.error("发送简单邮件异常=={}", e);
            }
        }
        else {
            logger.error("发送人为空具体信息{}", info);
        }
    }

    /**
     * 发送附件,牵扯文件的上传，着不好写唉，先不写
     */
    @Override
    public void sendAttachmentMail(EmailInfo info){}
}
